/**
 * verify token
 */

const jwt = require('jsonwebtoken')
const productToken  = require('../utils/produceToken')

module.exports = async(ctx, next) => {
	const auth = ctx.request.header.authorization

	if (!ctx.session) {
		ctx.throw(401, 'not login')
	}

	if (!auth) {
		ctx.throw(401, 'No token detected')
	}

	let tokenContent
	try {
		tokenContent = await jwt.verify(auth, productToken.getCode())
	} catch (err) {
		console.log(err)
		// Token 过期
		if (err.name === 'TokenExpiredError') {
			ctx.throw(401, 'Token expried')
		}
		// Token 验证失败
		ctx.throw(401, 'Invalid Token')
	}

	return await next()
}